<?php


namespace app\open\controller\bwc;

use app\open\service\PlayService;
use app\open\service\OrderService;
use app\common\controller\Api;
use think\Config;
use app\common\model\OrderProof;
use app\common\model\Collection;
use app\admin\model\Play as PlayModel;
use think\Db;
use think\Cache;
use app\admin\model\Shop;

/**
 * 活动
 * Class Play
 * @package app\api\controller
 */
class TaskAction extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected function _initialize() {
        parent::_initialize();
    }



    // 考虑新用户专享，只显示同城活动，美团官方
    // https://bdbdev.chbcplus.com/open/bwc/TaskAction/getList?id=887&sign=111&clientId=c4e71e7e7e1ea39f&latitude=30.330562&longitude=120.118332&timestamp=11&mobile=A55V0RFHOhPjlTN9V9mpDw%3D%3D&takeoutOrderNo=87655346534565477&orderNo=6582576439811966&orderImg=http://oss.chbcplus.com/front/20250811/61d16a278d6de82e9f1621007a084bfb.jpg&feedbackImg=http://oss.chbcplus.com/front/20250811/61d16a278d6de82e9f1621007a084bfb.jpg
    public function getList()
    {
        $params = $this->request->param();
        $pageSize = input('pageSize/d', 20);
        $page = input('pageNum/d', 1);
        $keywords = trim(input('keywords', '')); // 关键词
        if (!isset($params['sign']) || !isset($params['clientId']) || !isset($params['timestamp']) || !isset($params['mobile']) || !isset($params['longitude']) || !isset($params['latitude'])) $this->error('缺少关键参数');
        // 渠道验证
        $channel = Db::name('channel')->where(['clientId'=>$params['clientId'],'status'=>1])->find();
        if (!$channel) $this->error('关键参数不正确');
        // 签名验证
        // $sign = $params['sign'];
        // unset($params['sign']);
        // $comparesign = PlayService::sign($params,$channel['clientSecret']);
        // if ($comparesign!=$sign) $this->error('签名不正确');
        // // 时间验证
        // if (abs(time()-intval($params['timestamp']/1000))>=2) $this->error('请求已过期');
        // // 手机验证
        // $mobile = PlayService::aes_decrypt($params['mobile'],substr($params['clientId'], 0, 16), substr($params['clientId'], 0, 16));
        // if ($mobile===false) $this->error('手机号不正确');
        // 缓存key
        $key = md5($params['latitude'].$params['longitude'].$page.$pageSize.$keywords);
        $Redis = new \think\cache\driver\Redis();
        $data = $Redis->get($key);
        if (!$data) {
            // 验证经纬度
            $address = PlayService::point2address($params['latitude'],$params['longitude']);
            if ($address===false || !isset($address['address_component']['city'])) $this->error('无效的经纬度');
            $province = $address['address_component']['province'];
            $city = $address['address_component']['city'];
            $area = $address['address_component']['district'];
            $where = ['s.city'=>$city];
            // $where = ['s.city'=>['in',[$city,'杭州市']]];
            $where['g.super_play_no'] = 0;
            $where['pc.channel_id'] = 3;
            if ($keywords) {
                $where['g.shop_name'] = ['like','%'.$keywords.'%'];
            }
            $order = isset($newOrder) && $newOrder != '' ? $newOrder : 'distance asc,id desc';
            $data = (new PlayService())->getPlayList($where, $params['latitude'], $params['longitude'], $order, $page, '','',$pageSize);
            // 缓存到redis
            $Redis->set($key,$data,300);
        } else {
            // 修正库存
            foreach ($data as $key => $value) {
                if ($value['taskList']) {
                    foreach ($value['taskList'] as $k => $v) {
                        $res = $Redis->get('bdbplay'.$v['id']);
                        if ($res!==false) {
                            $data[$key]['taskList'][$k]['remainingQuota'] = $res;
                        }
                    }
                }
            }
        }
        $this->success('success', $data);
    }


    public function getDetail()
    {
        $params = $this->request->param();
        if (!isset($params['sign']) || !isset($params['clientId']) || !isset($params['timestamp']) || !isset($params['mobile']) || !isset($params['longitude']) || !isset($params['latitude']) || !$params['id']) $this->error('缺少关键参数');
        // 渠道验证
        $channel = Db::name('channel')->where(['clientId'=>$params['clientId'],'status'=>1])->find();
        if (!$channel) $this->error('关键参数不正确');
        // 签名验证
        // $sign = $params['sign'];
        // unset($params['sign']);
        // $comparesign = PlayService::sign($params,$channel['clientSecret']);
        // if ($comparesign!=$sign) $this->error('签名不正确');
        // 时间验证
        // if (abs(time()-intval($params['timestamp']/1000))>=2) $this->error('请求已过期');
        // // 手机验证
        // $mobile = PlayService::aes_decrypt($params['mobile'],substr($params['clientId'], 0, 16), substr($params['clientId'], 0, 16));
        // if ($mobile===false) $this->error('手机号不正确');
        $play = (new PlayService())->getPlayDetail($params['id'], $params['latitude'], $params['longitude']);
        if (!$play) $this->error('活动不存在');
        // $quota = Db::name('play_channel')->where(['play_id'=>$params['id'],'channel_id'=>$channel['id']])->value('quota');
        // $play['remainingQuota'] = $quota;
        $this->success('活动详情', $play);
    }

    /**
     * 报名
     * @param OrderService $orderService
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function apply()
    {
        $params = $this->request->param();
        if (!isset($params['sign']) || !isset($params['clientId']) || !isset($params['timestamp']) || !isset($params['mobile']) || !isset($params['longitude']) || !isset($params['latitude']) || !$params['id']) $this->error('缺少关键参数');
        // 渠道验证
        $channel = Db::name('channel')->where(['clientId'=>$params['clientId'],'status'=>1])->find();
        if (!$channel) $this->error('关键参数不正确');
        // 签名验证
        // $sign = $params['sign'];
        // unset($params['sign']);
        // $comparesign = PlayService::sign($params,$channel['clientSecret']);
        // if ($comparesign!=$sign) $this->error('签名不正确');
        // 时间验证
        // if (abs(time()-intval($params['timestamp']/1000))>=2) $this->error('请求已过期');
        // // 手机验证
        $mobile = PlayService::aes_decrypt($params['mobile'],substr($params['clientId'], 0, 16), substr($params['clientId'], 0, 16));
        // if ($mobile===false) $this->error('手机号不正确');
        $play = (new \app\admin\model\Play())->where('id', $params['id'])->find();
        if (empty($play)) $this->error('活动不存在');
        if ($play['chbcconsume'] <= 0) $this->error('活动名额已满');
        if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
        if ($play['play_status'] != 2) $this->error('活动未开始或已完结');
        // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
        // $userorder = order_count_read($userId);
        // if ($userorder<6) {
        //     $orderNum = (new \app\common\model\Order())->where([
        //         'user_id' => $userId,
        //         'create_dt' => ['>=',date('Y-m-d',time())],
        //         'order_status' => ['not in',[-1,-2,-4]]
        //     ])->count();
        //     if ($orderNum >= 2) $this->error('您的报名次数已用完');
        // } else {
        //     $orderNum = (new \app\common\model\Order())->where([
        //         'user_id' => $userId,
        //         'create_dt' => ['>=',date('Y-m-d',time())],
        //         'order_status' => ['not in',[-1,-2,-4]]
        //     ])->count();
        //     if ($orderNum >= 5) $this->error('您的报名次数已用完');
        // }
        // // 店铺是否禁止用户下单
        // $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
        // if ($shop['limited_user']) {
        //     $limited_user = trim($shop['limited_user'],'|');
        //     $limited_user_arr = explode('|', $limited_user);
        //     if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
        //         $this->error('您已超出该店铺点餐次数上限');
        //     }
        // }

        // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => $userId,
        //     'order_status' => ['in',[-5,-7,-8]]
        // ])->count();
        // if ($orderNum) {
        //     $this->error('您有未完成的订单，当前不能下单');
        // }
        //下单操作
        $orderService = new OrderService();
        $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>16,'int_prefix'=>6]);
        if (Db::name('play_order')->where(['play_order_no'=>$play_order_no])->find()) {
            $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>16,'int_prefix'=>6]);
        }
        $order = $orderService->createOrder($mobile, $play, $play_order_no,$channel);
        if ($order) {
            // 给渠道发通知，报名的状态为0
            if ($order['create_by']=='api') {
                $OrderService = new \app\open\service\OrderService();
                $OrderService->statusChange($order['wm_order_sn'],$order['play_order_no'],0,0,$order['actual_rebate_amt'],$order['is_yunzhan']);
            }
            $this->success('报名成功', ['orderNo'=>$order['play_order_no']]);
        }
        $this->error('报名失败');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 200, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }
}